﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DoubleH.Plugins;
using Table = FCNS.Data.Table;
using System.Diagnostics;
using System.Collections.ObjectModel;
using DoubleH.Utility;
using DoubleH.Utility.Configuration;
using System.Net.Mail;
using System.Net;
using System.Collections;

namespace SysConfig
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        FCNS.Data.Table.SysConfig sysConfig = FCNS.Data.Table.SysConfig.SysConfigParams;
        ObservableCollection<Table.GroupS> groupS = new ObservableCollection<Table.GroupS>(Table.GroupS.GetList(Table.GroupS.EnumFlag.操作员分类, Table.GroupS.EnumEnable.启用));
        Int64 selectedGroupIndex = -1;

        public MainWindow()
        {
            InitializeComponent();
        }

        public void Init(IEnumerable plugins)
        {
            dataGridExtExtension.ItemsSource = plugins;

            Table.UserS userS = Table.UserS.LoginUser;
            if (userS.GetAuthority("数据库配置") < Table.UserS.EnumAuthority.编辑)
            {
                tabItemDatabase.Visibility = Visibility.Collapsed;
                tabItemModel.Visibility = Visibility.Collapsed;
            }
            else
            {
                InitDatabase(true);
                InitModel(true);
            }

            if (userS.GetAuthority(DataTableText.系统配置) < Table.UserS.EnumAuthority.编辑)
                tabItemSys.Visibility = Visibility.Collapsed;
            else
                InitAppConfig(true);

            if (userS.GetAuthority("用户配置") < Table.UserS.EnumAuthority.编辑)
                tabItemUser.Visibility = Visibility.Collapsed;
            else
                InitOperatorVar();

            InitUserVar();
            InitUserEvent();
            InitUserConfig(true);

            tabControlAll.SelectedItem = tabItemUI;
        }

        #region 全局配置 模块配置
        private void InitDatabase(bool init)
        {
            if (init)
            {
                integerUpDownDecimalPlaces.Value = sysConfig.DecimalPlaces;
                doubleUpDownScore.Value = sysConfig.ScoreValue;
                integerUpDownSearchDataByUserConfig.Value = (int)sysConfig.GroupDataCount;

                checkBoxAutoAuditor.IsChecked = sysConfig.AutoAuditor;
                checkBoxAutoPost.IsChecked = sysConfig.AutoPost;
                checkBoxAutoMoney.IsChecked = sysConfig.AutoMoney;
                checkBoxProductRow.IsChecked = sysConfig.ProductRow;
                checkBoxPrintAfterSaveOrder.IsChecked = sysConfig.PrintAfterSaveOrder;
                checkBoxCanNotDeleteStoreOrderS.IsChecked = sysConfig.CanNotDeleteStoreOrderS;
                comboBox1OfflineSale.SelectedIndex=(int) sysConfig.PosOfflineMode;
                checkBoxCoupons.IsChecked = sysConfig.MoreCoupons;

                textBoxCompanyAddress.Text = sysConfig.CompanyAddress;
                textBoxCompanyEmail.Text = sysConfig.CompanyEmail;
                textBoxCompanyFax.Text = sysConfig.CompanyFax;
                textBoxCompanyName.Text = sysConfig.CompanyName;
                textBoxCompanyTel.Text = sysConfig.CompanyTel;
                textBoxCompanyWebSite.Text = sysConfig.CompanyWebSite;

                comboBoxEditMode.Items.Add(Table.SysConfig.EnumEditMode.权限分配);
                comboBoxEditMode.Items.Add(Table.SysConfig.EnumEditMode.用户组);
                comboBoxEditMode.Items.Add(Table.SysConfig.EnumEditMode.自己);
                comboBoxEditMode.SelectedIndex = (int)sysConfig.EditMode;

                comboBoxJieZhuan.SelectedIndex = (int)sysConfig.JieZhuanMode;
                integerUpDownJieZhuan.Value = (int)sysConfig.JieZhuanRi;
            }
            else
            {
                sysConfig.DecimalPlaces = integerUpDownDecimalPlaces.Value.Value;
                sysConfig.ScoreValue = doubleUpDownScore.Value.Value;
                sysConfig.GroupDataCount = (uint)integerUpDownSearchDataByUserConfig.Value.Value;

                sysConfig.PosOfflineMode =comboBox1OfflineSale.SelectedIndex;
                sysConfig.AutoAuditor = checkBoxAutoAuditor.IsChecked.Value;
                sysConfig.AutoPost = checkBoxAutoPost.IsChecked.Value;
                sysConfig.AutoMoney = checkBoxAutoMoney.IsChecked.Value;
                sysConfig.ProductRow = checkBoxProductRow.IsChecked.Value;
                sysConfig.PrintAfterSaveOrder = checkBoxPrintAfterSaveOrder.IsChecked.Value;
                sysConfig.CanNotDeleteStoreOrderS = checkBoxCanNotDeleteStoreOrderS.IsChecked.Value;
                sysConfig.MoreCoupons = checkBoxCoupons.IsChecked.Value;

                sysConfig.EditMode = comboBoxEditMode.SelectedIndex;

                sysConfig.CompanyAddress = textBoxCompanyAddress.Text;
                //sysConfig.CompanyEmail = textBoxCompanyEmail.Text;//在下面的验证处保存这个值
                sysConfig.CompanyFax = textBoxCompanyFax.Text;
                sysConfig.CompanyName = textBoxCompanyName.Text;
                sysConfig.CompanyTel = textBoxCompanyTel.Text;
                sysConfig.CompanyWebSite = textBoxCompanyWebSite.Text;

                sysConfig.JieZhuanMode = comboBoxJieZhuan.SelectedIndex;
                sysConfig.JieZhuanRi = integerUpDownJieZhuan.Value.Value;
            }
        }

        private void InitModel(bool init)
        {
            if (init)
            {
                //模块
                checkListBoxModel.DisplayMemberPath = "ModelText";
                checkListBoxModel.SelectedMemberPath = "Used";
                IEnumerable<Table.SysConfig.Model> models = Table.SysConfig.SysConfigParams.AllModel();
                checkListBoxModel.ItemsSource = models;
                foreach (Table.SysConfig.Model m in models)
                    SetModel(m, m.Used);

                //车辆
                checkBoxCarS.IsChecked = sysConfig.CarUsePaySShenHe;
                //采购
                checkBoxLastPurchasePrice.IsChecked = sysConfig.LastPurchasePrice;
                //批发
                checkBoxNegativeSales.IsChecked = sysConfig.NegativeSales;
                //零售
                checkBoxPosShenHe.IsChecked = sysConfig.PosShenHe;
                //仓库
                checkBoxLockQuantityWherePandian.IsChecked = sysConfig.LockQuantityWherePanDian;
                checkBoxCheckBarcode.IsChecked = sysConfig.CheckBarcode;
                //售后
                integerUpDownRequestTime.Value = (int)sysConfig.RequestTime;
                doubleUpDownKaoHeFenShu.Value = sysConfig.DefaultKaoHeFenShu;
                integerUpDownWeiBaoAlertDay.Value = (int)sysConfig.WeiBaoAlertDay;
                checkBoxBaoXiuHasSale.IsChecked = sysConfig.FanXiuHasSale;

                comboBoxMoneyAfterSales.Items.Add(Table.AfterSaleServiceS.EnumEnable.维护完工);
                comboBoxMoneyAfterSales.Items.Add(Table.AfterSaleServiceS.EnumEnable.回访反馈);
                comboBoxMoneyAfterSales.SelectedItem = sysConfig.CalcMoneyAfterSaleServiceS;
                //财务
                integerUpDownMoneyAlertDayFu.Value = (int)sysConfig.FuKuanAlertDay;
                integerUpDownMoneyAlertDayShou.Value = (int)sysConfig.ShouKuanAlertDay;
                //报表
                timePickerStart.Value = DateTime.ParseExact(DoubleHConfig.UserConfig.WorkStart, FCNS.Data.DbDefine.timeFormat, null);
                timePickerEnd.Value = DateTime.ParseExact(DoubleHConfig.UserConfig.WorkEnd, FCNS.Data.DbDefine.timeFormat, null);

                InitDatabaseParamEvent();
            }
            else
            {
                //车辆
                sysConfig.CarUsePaySShenHe = checkBoxCarS.IsChecked.Value;
                //采购
                sysConfig.LastPurchasePrice = checkBoxLastPurchasePrice.IsChecked.Value;
                //批发
                sysConfig.NegativeSales = checkBoxNegativeSales.IsChecked.Value;
                //零售
                sysConfig.PosShenHe = checkBoxPosShenHe.IsChecked.Value;
                //仓库
                sysConfig.LockQuantityWherePanDian = checkBoxLockQuantityWherePandian.IsChecked.Value;
                sysConfig.CheckBarcode = checkBoxCheckBarcode.IsChecked.Value;
                //售后
                sysConfig.RequestTime = integerUpDownRequestTime.Value.Value;
                sysConfig.DefaultKaoHeFenShu = doubleUpDownKaoHeFenShu.Value.Value;
                sysConfig.WeiBaoAlertDay = integerUpDownWeiBaoAlertDay.Value.Value;
                sysConfig.FanXiuHasSale = checkBoxBaoXiuHasSale.IsChecked.Value;
                sysConfig.CalcMoneyAfterSaleServiceS = (Table.AfterSaleServiceS.EnumEnable)comboBoxMoneyAfterSales.SelectedItem;
                //财务
                sysConfig.FuKuanAlertDay = integerUpDownMoneyAlertDayFu.Value.Value;
                sysConfig.ShouKuanAlertDay = integerUpDownMoneyAlertDayShou.Value.Value;
                //报表
                DoubleHConfig.UserConfig.WorkStart = timePickerStart.Value.Value.ToString(FCNS.Data.DbDefine.timeFormat);
                DoubleHConfig.UserConfig.WorkEnd = timePickerEnd.Value.Value.ToString(FCNS.Data.DbDefine.timeFormat);
            }
        }

        private void InitDatabaseParamEvent()
        {
            checkListBoxModel.ItemSelectionChanged += (ss, ee) => SetModel(ee.Item as Table.SysConfig.Model, ee.IsSelected);
            tabControlAll.SelectionChanged += (ss, e) => buttonAuthority.IsEnabled = (tabControlAll.SelectedItem == tabItemUser);
        }

        private void SetModel(Table.SysConfig.Model model, bool used)
        {
            Debug.Assert(model != null);
            //if (model.ModelText == Table.SysConfig.EnumModel.车辆租赁 && used)
            //{
            //    ListBoxItem item = (ListBoxItem)checkListBoxModel.FindName(Table.SysConfig.EnumModel.车辆管理.ToString());
            //    item.IsSelected = true;
            //}
            switch (model.ModelText)
            {
                case Table.SysConfig.EnumModel.采购进货: groupBoxPurchase.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.仓库管理: groupBoxStore.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.批发销售: groupBoxSales.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.POS零售: groupBoxPos.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.售后服务: groupBoxAfterSaleService.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.车辆管理: groupBoxCarS.IsEnabled = used;break;
                case Table.SysConfig.EnumModel.财务管理: groupBoxPayS.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.物流快递: groupBoxWuLiu.IsEnabled = used; break;
                case Table.SysConfig.EnumModel.报表中心: break;
            }
            //tabControlUser.Visibility = tabControlUser.HasItems ? Visibility.Visible : Visibility.Hidden;
        }
        #endregion

        #region 程序配置
        private void InitAppConfig(bool init)
        {
            if (init)
            {
                foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        comboBoxIP.Items.Add(ip.ToString());

                comboBoxIP.Text = DoubleHConfig.AppConfig.LocalIP;

                groupBoxDhServer.IsEnabled = (Table.UserS.LoginUser.UserNO == "root"); 

                integerUpDownServerPort.Value = DoubleHConfig.AppConfig.ServerPort;

                integerUpDownReLoadTime.Value = DoubleHConfig.AppConfig.ReloadDataTime;

                checkBoxAutoUpdate.IsChecked = DoubleHConfig.AppConfig.CheckUpdate;
                checkBoxTabTip.IsChecked = DoubleHConfig.AppConfig.AutoLoadTabTip;

                checkBoxAutoRunServer.IsChecked = DoubleHConfig.AppConfig.AutoRunServer;

                integerUpDownDelayTime.Value = DoubleHConfig.AppConfig.DelayTime;
                integerUpDownSearchThreshold.Value = DoubleHConfig.AppConfig.SearchThreshold;
            }
            else
            {
                DoubleHConfig.AppConfig.LocalIP = comboBoxIP.Text; 

                DoubleHConfig.AppConfig.ServerPort = integerUpDownServerPort.Value.Value;
                DoubleHConfig.AppConfig.ReloadDataTime = integerUpDownReLoadTime.Value.Value;

                DoubleHConfig.AppConfig.CheckUpdate = checkBoxAutoUpdate.IsChecked.Value;
                DoubleHConfig.AppConfig.AutoLoadTabTip = checkBoxTabTip.IsChecked.Value;

                DoubleHConfig.AppConfig.AutoRunServer = checkBoxAutoRunServer.IsChecked.Value;


                DoubleHConfig.AppConfig.DelayTime = integerUpDownDelayTime.Value.Value;
                DoubleHConfig.AppConfig.SearchThreshold = integerUpDownSearchThreshold.Value.Value;
            }
        }

        private void InitExtension()
        {
            dataGridExtExtension.SelectionChanged += (ss, ee) =>
            {
                if (dataGridExtExtension.SelectedItem == null)
                    return;

                DoubleH.Plugins.PluginInfo info = dataGridExtExtension.SelectedItem as DoubleH.Plugins.PluginInfo;
                textBlockExtension.Text = info.Description;
            };
            labelExtension.MouseDown += (ss, ee) => System.Diagnostics.Process.Start("http://www.fcnsoft.com/extension/default.html");
        }

        #endregion

        #region 用户配置
        private void InitUserVar()
        {
            comboBoxScheduleSFlag.ItemsSource = Enum.GetNames(typeof(Table.ScheduleS.EnumFlag));

            comboBoxLanguage.Items.Add("简体中文");
            foreach (string fi in System.IO.Directory.GetFiles(FCNS.Data.DbDefine.langDir, "*.lng",System.IO.SearchOption.TopDirectoryOnly))
                comboBoxLanguage.Items.Add(System.IO.Path.GetFileName(fi));
        }

        private void InitUserConfig(bool init)
        {
            if (init)
            {
                checkBoxScheduleS.IsChecked = DoubleHConfig.UserConfig.ScheduleSUseImageForFlag;
                checkBoxMessage.IsChecked = DoubleHConfig.UserConfig.ShowMessageWindow;

                integerUpDownAlertTimeByUserConfig.Value = DoubleHConfig.UserConfig.AlertTime;

                checkBoxSynchronousData.IsChecked = DoubleHConfig.UserConfig.SynchronousData;

                textBoxSmtpAddress.Text = DoubleHConfig.UserConfig.EmailSmtp;
                textBoxEmailName.Text = DoubleHConfig.UserConfig.EmailName;
                passwordBoxEmailPwd.Password = DoubleHConfig.UserConfig.EmailPwd;
                checkBoxEmailSsl.IsChecked = DoubleHConfig.UserConfig.EmailSsl;
                integerUpDownPort.Value = DoubleHConfig.UserConfig.EmailPort;

                comboBoxUserProductPrice.SelectedIndex = DoubleHConfig.UserConfig.ProductPrice;

                comboBoxLanguage.SelectedItem = DoubleHConfig.UserConfig.Language;
                colorPickerAlternatingRowBackground.SelectedColor = (Color)ColorConverter.ConvertFromString(DoubleHConfig.AppConfig.BrushString);

                InitExtension();
            }
            else
            {
                DoubleHConfig.UserConfig.ScheduleSUseImageForFlag = checkBoxScheduleS.IsChecked.Value;
                DoubleHConfig.UserConfig.ShowMessageWindow = checkBoxMessage.IsChecked.Value;

                DoubleHConfig.UserConfig.AlertTime = integerUpDownAlertTimeByUserConfig.Value.Value;

                DoubleHConfig.UserConfig.SynchronousData = (bool)checkBoxSynchronousData.IsChecked;

                DoubleHConfig.UserConfig.EmailSmtp = textBoxSmtpAddress.Text;
                DoubleHConfig.UserConfig.EmailName = textBoxEmailName.Text;
                DoubleHConfig.UserConfig.EmailPwd = passwordBoxEmailPwd.Password;
                DoubleHConfig.UserConfig.EmailSsl = checkBoxEmailSsl.IsChecked.Value;
                DoubleHConfig.UserConfig.EmailPort = integerUpDownPort.Value.Value;

                DoubleHConfig.UserConfig.ProductPrice = comboBoxUserProductPrice.SelectedIndex;
                if (comboBoxLanguage.SelectedItem != null)
                    DoubleHConfig.UserConfig.Language = comboBoxLanguage.SelectedItem.ToString();

                DoubleHConfig.AppConfig.BrushString = colorPickerAlternatingRowBackground.SelectedColorText;
            }
        }

        private void InitUserEvent()
        {
            comboBoxScheduleSFlag.SelectionChanged += (ss, ee) => ScheduleSFlagChanged();
            buttonScheduleSImage.Click += (ss, ee) => ScheduleSImageClick();
            buttonSave.Click += (ss, ee) => Save();
        }

        private void ScheduleSFlagChanged()
        {
            switch (comboBoxScheduleSFlag.SelectedIndex)
            {
                case 0: buttonScheduleSImage.Content = string.IsNullOrEmpty(DoubleHConfig.UserConfig.ScheduleImage0) ? "选择图片" : DoubleHConfig.UserConfig.ScheduleImage0; break;
                case 1: buttonScheduleSImage.Content = string.IsNullOrEmpty(DoubleHConfig.UserConfig.ScheduleImage1) ? "选择图片" : DoubleHConfig.UserConfig.ScheduleImage1; break;
                case 2: buttonScheduleSImage.Content = string.IsNullOrEmpty(DoubleHConfig.UserConfig.ScheduleImage2) ? "选择图片" : DoubleHConfig.UserConfig.ScheduleImage2; break;
                case 3: buttonScheduleSImage.Content = string.IsNullOrEmpty(DoubleHConfig.UserConfig.ScheduleImage3) ? "选择图片" : DoubleHConfig.UserConfig.ScheduleImage3; break;
            }
        }

        private void ScheduleSImageClick()
        {
            buttonScheduleSImage.Content = DoubleH.Utility.IO.FileTools.GetFile(true, ".jpg", ".bmp", ".gif", ".png");
            switch (comboBoxScheduleSFlag.SelectedIndex)
            {
                case 0: DoubleHConfig.UserConfig.ScheduleImage0 = buttonScheduleSImage.Content.ToString(); break;
                case 1: DoubleHConfig.UserConfig.ScheduleImage1 = buttonScheduleSImage.Content.ToString(); break;
                case 2: DoubleHConfig.UserConfig.ScheduleImage2 = buttonScheduleSImage.Content.ToString(); break;
                case 3: DoubleHConfig.UserConfig.ScheduleImage3 = buttonScheduleSImage.Content.ToString(); break;
            }
        }

        private void Save()
        {
            if (Table.UserS.LoginUser.GetAuthority("数据库配置") > Table.UserS.EnumAuthority.查看 && (string.IsNullOrEmpty(textBoxCompanyEmail.Text) || !textBoxCompanyEmail.Text.Contains("@") || !textBoxCompanyEmail.Text.Contains(".")))
            {
                MessageWindow.Show("电子邮箱不能为空");
                return;
            }
            if (textBoxCompanyEmail.Text != sysConfig.CompanyEmail || textBoxEmailName.Text != DoubleHConfig.UserConfig.EmailName)
            {
                sysConfig.CompanyEmail = textBoxCompanyEmail.Text;
                textBoxCompanyEmail.Clear();
            }

            Table.UserS userS = Table.UserS.LoginUser;
            if (userS.GetAuthority("数据库配置") > Table.UserS.EnumAuthority.查看)
            {
                InitDatabase(false);
                InitModel(false);
                if (Table.SysConfig.SysConfigParams.PosOfflineMode > 0)
                    Table.SysConfig.SysConfigParams.NegativeSales = true;

                sysConfig.Update();
            }
            if (userS.GetAuthority(DataTableText.系统配置) > Table.UserS.EnumAuthority.查看)
            {
                InitAppConfig(false);
                ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
            }
           
            InitUserConfig(false);
            if (string.IsNullOrEmpty(textBoxCompanyEmail.Text))
            {
                FCNS.Data.Utility u = new FCNS.Data.Utility();
                Action<string> action = u.SendMail;
                action.BeginInvoke(textBoxEmailName.Text, null, null);
            }

            this.Close();
        }
        #endregion

        #region  操作员
        private void InitContextMenu()
        {
            ContextMenu cmGroup = new ContextMenu();
            MenuItem mig1 = new MenuItem();
            mig1.Header = "新增用户组";
            mig1.Click += (ss, ee) => { NewOperatorGroup(); };
            cmGroup.Items.Add(mig1);
            MenuItem mig2 = new MenuItem();
            mig2.Header = "编辑用户组";
            mig2.Click += (ss, ee) => { EditOperatorGroup(); };
            cmGroup.Items.Add(mig2);
            MenuItem mig3 = new MenuItem();
            mig3.Header = "删除用户组";
            mig3.Click += (ss, ee) => { DeleteOperatorGroup(); };
            cmGroup.Items.Add(mig3);
            listBoxGroup.ContextMenu = cmGroup;

            ContextMenu cmUser = new ContextMenu();
            MenuItem miu1 = new MenuItem();
            miu1.Header = "新增用户";
            miu1.Click += (ss, ee) => { NewOperator(); };
            cmUser.Items.Add(miu1);
            MenuItem miu2 = new MenuItem();
            miu2.Header = "编辑用户";
            miu2.Click += (ss, ee) => { EditOperator(); };
            cmUser.Items.Add(miu2);
            //MenuItem miu3 = new MenuItem();
            //miu3.Header = "删除用户";
            //miu3.Click += (ss, ee) => { DeleteUser(); };
            //cmUser.Items.Add(miu3);
            listViewUser.ContextMenu = cmUser;
        }

        private void InitOperatorVar()
        {
            listViewUser.DisplayMemberPath = "Name";
            listViewUser.SelectedValuePath = "Id";

            listBoxGroup.DisplayMemberPath = "Name";
            listBoxGroup.SelectedValuePath = "Id";
            listBoxGroup.ItemsSource = groupS;

            InitContextMenu();
            InitOperatorEvent();
        }

        private void InitOperatorEvent()
        {
            listBoxGroup.SelectionChanged += (ss, ee) => ChangeOperatorGroup();
            listBoxGroup.MouseDoubleClick += (ss, ee) => EditOperatorGroup();
            listViewUser.MouseDoubleClick += (ss, ee) => EditOperator();
            listViewUser.SelectionChanged += (ss, ee) => InitOperatorAuthority();
            buttonAuthority.Click += (ss, ee) => SaveOperatorAuthority();
        }

        private void ChangeOperatorGroup()
        {
            if (listBoxGroup.SelectedItem != null)
            {
                selectedGroupIndex = (Int64)listBoxGroup.SelectedValue;
                listViewUser.ItemsSource = Table.UserS.GetList(selectedGroupIndex, null);
            }
        }

        private void NewOperatorGroup()
        {
            GroupS.MainWindow mw = new GroupS.MainWindow();
            mw.Init(Table.GroupS.EnumFlag.操作员分类, null);
            mw.ShowDialog();
            groupS.Add(mw.NewGroupS);
        }

        private void EditOperatorGroup()
        {
            if (listBoxGroup.SelectedItem == null)
                return;

            GroupS.MainWindow mw = new GroupS.MainWindow();
            mw.Init(Table.GroupS.EnumFlag.操作员分类, listBoxGroup.SelectedItem as Table.GroupS);
            mw.ShowDialog();
        }

        private void DeleteOperatorGroup()
        {
            if (listBoxGroup.SelectedItem == null)
                return;

            Table.GroupS gs = (Table.GroupS)listBoxGroup.SelectedItem;
            //Table.DataTableS.EnumDatabaseStatus result = gs.ZuoFei();
            //if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
            //    groupS.Remove(gs);
            //else
            MessageWindow.Show(gs.ZuoFei().ToString());
        }

        private void NewOperator()
        {
            WindowUser wu = new WindowUser();
            wu.Init(null);
            wu.ShowDialog();
            listViewUser.ItemsSource = Table.UserS.GetList(selectedGroupIndex, null);
        }

        private void EditOperator()
        {
            if (listViewUser.SelectedItem == null)
                return;

            WindowUser wu = new WindowUser();
            wu.Init(listViewUser.SelectedItem as Table.UserS);
            wu.ShowDialog();
            listViewUser.ItemsSource = Table.UserS.GetList(selectedGroupIndex, null);
        }

        private void DeleteOperator()
        {
            if (listViewUser.SelectedItem == null)
                return;

            MessageWindow.Show(((Table.UserS)listViewUser.SelectedItem).ZuoFei().ToString());
            //listViewUser.ItemsSource = Table.UserS.GetListForCorS(selectedGroupIndex, null);
        }

        private void InitOperatorAuthority()
        {
            if (listViewUser.SelectedItem == null)
                return;

            Table.UserS us = listViewUser.SelectedItem as Table.UserS;
            uCauthoritySystem.Items.Clear();
            uCauthorityPos.Items.Clear();
            uCauthorityReport.Items.Clear();

            if (us.Flag == Table.UserS.EnumFlag.经办人)
            {
                buttonAuthority.IsEnabled = false;
                return;
            }
            buttonAuthority.IsEnabled = true;

            List<DataTableText> dtMenu = new List<DataTableText>();
            List<DataTableText> dtReport= new List<DataTableText>();
            SearchAuthority(DataTableText.系统配置, DataTableText.待办事项, dtMenu);
            SearchAuthority(DataTableText.商品毛利表, DataTableText.营业额, dtReport);
            if (sysConfig.UsePurchaseOrderS)
            {
                SearchAuthority(DataTableText.可采购商品, DataTableText.自动补货, dtMenu);
                SearchAuthority(DataTableText.采购统计表, DataTableText.采购价格变动情况表, dtReport);
            }
            if (sysConfig.UseStoreS)
            {
                SearchAuthority(DataTableText.仓库商品, DataTableText.盘点单, dtMenu);
            }
            if (sysConfig.UseSalesOrderS)
            {
                SearchAuthority(DataTableText.可销售商品, DataTableText.赠品出库单, dtMenu);
                SearchAuthority(DataTableText.销售统计表, DataTableText.销售价格变动情况表, dtReport);
            }
            if (sysConfig.UsePos )
            {
                SearchAuthority(DataTableText.POS机器号, DataTableText.客存明细, dtMenu);
                SearchAuthority(DataTableText.交班明细表, DataTableText.零售明细表, dtReport);
                uCauthorityPos.Init(us, true, Enum.GetNames(typeof(Table.PosS.EnumAuthority)));
            }
            if (sysConfig.UseAfterSaleServiceS)
            {
                SearchAuthority(DataTableText.客户报修, DataTableText.服务评价, dtMenu);
                SearchAuthority(DataTableText.售后统计表, DataTableText.故障库, dtReport);
            }
            if (sysConfig.UsePayS)
            {
                SearchAuthority(DataTableText.支付方式, DataTableText.可收支单据, dtMenu);
                SearchAuthority(DataTableText.账户余额表, DataTableText.发票明细表, dtReport);
            }
            if (sysConfig.UseItDbS)
                SearchAuthority(DataTableText.浏览数据, DataTableText.标记, dtMenu);

            if (sysConfig.UseProjectS)
                SearchAuthority(DataTableText.项目列表, DataTableText.任务类型, dtMenu);
           
            if (sysConfig.UseCarS)
            {
                SearchAuthority(DataTableText.车辆档案, DataTableText.投保记录, dtMenu);
                SearchAuthority(DataTableText.车辆成本, DataTableText.车辆成本, dtReport);
            }
            if (sysConfig.UseWuLiuS)
                SearchAuthority(DataTableText.物流公司, DataTableText.批发物流跟踪, dtMenu);

            uCauthoritySystem.Init(us, false, dtMenu.ToArray());
            uCauthorityReport.Init(us, true, dtReport.ToArray());
            uCauthorityReport.IsEnabled = us.Flag == Table.UserS.EnumFlag.操作员;
            uCauthoritySystem.IsEnabled = uCauthorityReport.IsEnabled;
            uCauthorityPos.IsEnabled = us.Flag == Table.UserS.EnumFlag.POS操作员;
        }

        private void SaveOperatorAuthority()
        {
            if (listViewUser.SelectedItem == null)
                return;

            Table.UserS us = (Table.UserS)listViewUser.SelectedItem;
            us.Authority.Clear();
            foreach (UC.UCauthority.Authority au in uCauthoritySystem.Items)
                us.Authority.Add(au.DataTableText, au.EA);
            foreach (UC.UCauthority.Authority au in uCauthorityReport.Items)
                us.Authority.Add(au.DataTableText, au.EA);
            foreach (UC.UCauthority.Authority au in uCauthorityPos.Items)
                us.Authority.Add(au.DataTableText, au.EA);

            MessageWindow.Show(us.UpdateAuthority().ToString());
        }

        private void SearchAuthority(DataTableText start, DataTableText end, List<DataTableText> dtt)
        {
            for (DataTableText dt = start; dt <= end; dt++)
                dtt.Add(dt);
        }
        #endregion
    }
}